package cn.personal.study.web.rest;

import java.io.IOException;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import cn.personal.study.domain.dto.request.UpdateUserRequestDTO;
import cn.personal.study.services.UserService;

/**
 * 用户资源
 *
 * @author duliurui
 */
@RestController
@RequestMapping("/users")
public class UserResources {

    @Resource(name = "userService")
    private UserService userService;

    @PutMapping(value = "/{userId}")
    public ResponseEntity<Boolean> updateUser(@PathVariable("userId") String userId,
                                     @RequestBody UpdateUserRequestDTO updateUserRequestDTO) throws SQLException {
        return ResponseEntity.ok(userService.updateUser(updateUserRequestDTO));
    }

    @GetMapping(value = "/{userId}")
    public ModelAndView viewUser(@PathVariable("userId") String userId) {
        ModelAndView model = new ModelAndView("userForm");
        model.addObject("user", userService.getUser(userId));

        return model;
    }

    @ExceptionHandler(Exception.class)
    public void exception(Exception e, HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("exception", e);
        // 定向到系统异常展示页面
        RequestDispatcher rd = request.getRequestDispatcher("/error.jsp");
        request.setAttribute("errorMsg", e.getMessage());
        rd.forward(request, response);
    }
}
